<template>
  <div class="hr-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">HR管理</h1>
        <p class="page-desc">管理企业HR用户账号和权限</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          添加HR
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入HR姓名" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="激活" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- HR列表 -->
    <el-card class="table-card">
      <el-table :data="tableData" v-loading="loading" stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" fixed />

        <!-- HR信息 -->
        <el-table-column label="HR信息" min-width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="40" :src="row.avatar">
                <el-icon>
                  <User />
                </el-icon>
              </el-avatar>
              <div class="info-content">
                <div class="user-name">{{ row.name }}</div>
                <div class="user-email">{{ row.email }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 角色权限 -->
        <el-table-column label="角色" width="120">
          <template #default="{ row }">
            <el-tag type="warning">
              {{ getRoleName(row.role) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 管理权限 -->
        <el-table-column label="管理权限" min-width="200">
          <template #default="{ row }">
            <div class="permissions">
              <el-tag v-for="permission in row.permissions" :key="permission" size="small" class="permission-tag">
                {{ getPermissionName(permission) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <!-- 负责职位数 -->
        <el-table-column label="负责职位" width="100">
          <template #default="{ row }">
            <el-link type="primary" @click="handleViewJobs(row)">
              {{ row.jobCount }}个职位
            </el-link>
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '激活' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>

        <!-- 最后登录 -->
        <el-table-column label="最后登录" width="180">
          <template #default="{ row }">
            {{ row.lastLoginAt ? formatDate(row.lastLoginAt) : '从未登录' }}
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              <el-icon>
                <View />
              </el-icon>
              查看
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-button type="warning" link @click="handlePermissions(row)">
              <el-icon>
                <Key />
              </el-icon>
              权限
            </el-button>
            <el-button :type="row.status === 'active' ? 'warning' : 'success'" link @click="handleToggleStatus(row)">
              <el-icon>
                <Switch />
              </el-icon>
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link>
              <el-icon>
                <Remove />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 添加/编辑HR对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="650px" @close="handleDialogClose">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入HR姓名" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEdit">
          <el-input v-model="formData.confirmPassword" type="password" placeholder="请确认密码" show-password />
        </el-form-item>

        <el-form-item label="管理权限" prop="permissions">
          <el-checkbox-group v-model="formData.permissions">
            <el-checkbox label="job_management">职位管理</el-checkbox>
            <el-checkbox label="candidate_management">候选人管理</el-checkbox>
            <el-checkbox label="interview_management">面试管理</el-checkbox>
            <el-checkbox label="offer_management">Offer管理</el-checkbox>
            <el-checkbox label="employee_management">员工管理</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarUpload">
            <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  User,
  View,
  Edit,
  Key,
  Switch
} from '@element-plus/icons-vue'
import usePageState from './hooks/usePageState'
import type { HRBase } from '@/types'

const {
  loading,
  submitLoading,
  dialogVisible,
  isEdit,
  formRef,
  searchForm,
  pagination,
  tableData,
  formData,
  formRules
} = usePageState()

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑HR' : '添加HR')

// 方法定义

/**
 * 获取角色名称
 */
const getRoleName = (role: string) => {
  const roleMap: Record<string, string> = {
    'Recruiter': '企业HR'
  }
  return roleMap[role] || role
}

/**
 * 获取权限名称
 */
const getPermissionName = (permission: string) => {
  const permissionMap: Record<string, string> = {
    'job_management': '职位管理',
    'candidate_management': '候选人管理',
    'interview_management': '面试管理',
    'offer_management': 'Offer管理',
    'employee_management': '员工管理'
  }
  return permissionMap[permission] || permission
}

/**
 * 格式化日期
 */
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    email: '',
    status: ''
  })
  handleSearch()
}

/**
 * 添加HR
 */
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

/**
 * 查看HR详情
 */

const handleView = (row: HRBase) => {
  ElMessage.info(`查看HR：${row.name}`)
  // TODO: 实现查看详情功能
}

/**
 * 编辑HR
 */

const handleEdit = (row: HRBase) => {
  isEdit.value = true
  Object.assign(formData, {
    id: row.id,
    name: row.name,
    email: row.email,
    permissions: [...row.permissions],
    avatar: row.avatar
  })
  dialogVisible.value = true
}

/**
 * 管理权限
 */

const handlePermissions = (row: HRBase) => {
  ElMessage.info(`管理权限：${row.name}`)
  // TODO: 实现权限管理功能
}

/**
 * 查看负责的职位
 */

const handleViewJobs = (row: HRBase) => {
  ElMessage.info(`查看${row.name}负责的职位`)
  // TODO: 跳转到职位列表页面，筛选该HR负责的职位
}

/**
 * 切换状态
 */

const handleToggleStatus = (row: HRBase) => {
  const action = row.status === 'active' ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确定要${action}HR「${row.name}」吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    row.status = row.status === 'active' ? 'inactive' : 'active'
    ElMessage.success(`${action}成功`)
    // TODO: 调用API更新状态
  })
}

/**
 * 分页大小改变
 */
const handleSizeChange = (size: number) => {
  pagination.size = size
  loadData()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

/**
 * 对话框关闭
 */
const handleDialogClose = () => {
  resetForm()
}

/**
 * 重置表单
 */
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    email: '',
    password: '',
    confirmPassword: '',
    permissions: [],
    avatar: ''
  })
  formRef.value?.clearValidate()
}

/**
 * 头像上传前验证
 */
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

/**
 * 处理头像上传
 */

const handleAvatarUpload = (options: { file: Blob }) => {
  // TODO: 实现头像上传逻辑
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.avatar = e.target?.result as string
  }
  reader.readAsDataURL(options.file)
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true

    // TODO: 调用API保存数据
    setTimeout(() => {
      submitLoading.value = false
      dialogVisible.value = false
      ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
      loadData()
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

/**
 * 加载数据
 */
const loadData = () => {
  loading.value = true
  // TODO: 调用API获取数据
  setTimeout(() => {
    pagination.total = 2
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.hr-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 4px 0;
}

.page-desc {
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-content {
  flex: 1;
}

.user-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.user-email {
  font-size: 12px;
  color: #909399;
}

.permissions {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.permission-tag {
  margin: 0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }

  .header-right {
    align-self: stretch;
  }
}
</style>
